from flask import Blueprint, request, render_template, redirect, session, make_response
from models import *

blue = Blueprint("blue", __name__)


@blue.route("/addstudent", methods=["GET", "POST"])
def addstudent():
    numid = Student.query.all()
    if request.method == "GET":
        return render_template("addstudent.html")
    else:
        num = request.form.get("num")
        name = request.form.get("name")
        gender = request.form.get("gender")
        pic = request.files.get("pic")
        if num in numid:
            return {"msg": "该编号已存在，请重新添加"}
        else:
            pic.save("static/upload/" + pic.filename)
            students = Student(num=num, name=name, gender=gender,
                               pic="/static/upload/" + pic.filename)
            db.session.add(students)
            db.session.commit()
            return {"msg": "添加成功"}


from flask_sqlalchemy import Pagination


@blue.route("/studentlist")
def studentlist():
    pag_num = int(request.args.get("pag_num", 1))
    per_num = 2
    pagination = Student.query.paginate(pag_num, per_num)
    return render_template("studentlist.html", list=pagination)


@blue.route("/info")
def info():
    id = request.args.get("id")
    student = Student.query.filter(Student.id == id).first()
    return render_template("info.html", student=student)


@blue.app_template_filter("genderes")
def genderes(value):
    if value == "男":
        value = "man"
        return value
    else:
        value = "woman"
        return value


# @blue.after_app_request
# # def after_app_request(response):
# #     # response = make_response(request.url.format())
# #     response = request.path.format()
# #     print(response)
# #     # log = Log(url=response)
# #     # db.session.add(log)
# #     # db.session.commit()
# #     return response

@blue.after_request
def teardown_request(response):
    # response = make_response(request.path.format())
    url = request.url
    print(url)
    log = Log(url=url)
    db.session.add(log)
    db.session.commit()
    return response
